<?php

    /**
     * Created by PhpStorm.
     * User: jiayanxiu
     * Date: 15/6/4
     * Time: 14:39
     */
    class SearchApp extends MallbaseApp
    {

        private $size = 10;
        private $common;

        /**
         * 构造函数
         */
        public function __construct ()
        {
            $this->common = new CommonApp();
        }

        /**
         * 新版支持讯搜搜索接口
         * @author  lz
         * @date    2016-2-24
         *       // 多选 价格,品牌,分类
         * @example content={work?}&cate_id={id,id,id,id?}&brand_id={id,id,id,id?}&price_id={id,id,id,id?}
         */
        public function xunsearch ()
        {
            $action = '迅搜搜索';
            setLogParameter($action);
            $method = strtoupper ( $_SERVER[ 'REQUEST_METHOD' ] );
            if ( $method != 'GET' )
            {
                $this->ajax_return ( FLAG_ERROR, '非法操作！' );
            }
            $brand = $store = $cate = '';
            // 搜索关键字
            // 多关键字用空格份
            if ( $content = $this->get_gp ( 'content', 'G' ) )
            {
                $content = '( ' . str_replace ( ' ', ' AND ', trim ( $content ) ) . ' )';
            }
            /*$user_id = $this->get_gp('user_id', 'G');
            $user_id = $user_id?$user_id:0;*/
            $user_id = $this->checkLogin();     //检验是否登录 
            // 分页
            $offset = $this->get_gp ('offset','G');
            $offset = $offset ? intval($offset) : 0;
            $size   = $this->get_gp ('size','G')?:10;
            // 筛选
            $filter = $this->get_gp ( 'filter', 'G' );
            // 品牌
            // 多品牌用半角逗号间隔
            if ( $brand_id = $this->get_gp ( 'brand_id', 'G' ) )
            {
                if ( stristr($brand_id,',') !== false )
                {
                    foreach ( explode ( ',', $brand_id ) as $temp )
                    {
                        $brand .= sprintf ( ' brand_id:%u OR', $temp );
                    }
                    $brand = '( ' . substr ( $brand, 0, - 3 ) . ' )';
                }

            }
            // 分类
            // 多分类用半角逗号间隔
            if( $cate_id = $this->get_gp ( 'cate_id', 'G' ) )
            {
                //判断是不是多个分类
                if ( stristr($cate_id,',') !== false )
                {
                    foreach ( explode ( ',', $cate_id ) as $temp )
                    {
                        $cate .= vsprintf ( ' ( cate_id_one:%u OR cate_id_two:%u OR cate_id_three:%u ) OR', array_fill (0,3,$temp) );
                    }

                }else{
                    $cate .= vsprintf ( ' ( cate_id_one:%u OR cate_id_two:%u OR cate_id_three:%u ) OR',array_fill (0,3,$cate_id));
                }
                $cate = '( ' . substr ( $cate, 0, - 3 ) . ' )';
            }
            // 价格
            $min = $this->get_gp ( 'min', 'G' );//最小价格
            $max = $this->get_gp ( 'max', 'G' );//最大价格
            // 排序
            $sort = $this->get_gp ( 'sort', 'G' ); //排序,1:上架时间,2:价钱从高到低,3:价钱从底到高,4:销量最高排序,5:喜欢的最多
            $sort = $sort?$sort:1;
            if ( $store_id = $this->get_gp ( 'store_id', 'G' ) )
            {
                if ( stristr($store_id,',') !== false )
                {
                    foreach ( explode ( ',', $store_id ) as $temp )
                    {
                        $store .= vsprintf ( ' store_id:%u OR', $temp );
                    }
                }else{
                        $store .= vsprintf ( ' store_id:%u OR', $store_id );
                }
                $store = '( ' . substr ( $store, 0, - 3 ) . ' )';
            }

            //调用讯搜搜索
            //echo $offset/$size;die;
            $res = $this->searching ( $content, $cate, $brand, $min,$max, $sort, $store,$offset);
            $model  = m ( 'goods' );
            $brands = array();
            if($res['goods'])
            {
                foreach ( $res[ 'brandIds' ] as $key => $val )
                {
                    $sql      = "SELECT brand_name,en_name FROM " . DB_PREFIX . "brand WHERE brand_id='{$key}'";
                    $brand    = $model->getRow ( $sql );
                    $brand    = $brand[ 'brand_name' ] ? $brand[ 'brand_name' ] : $brand[ 'en_name' ];
                    $brands[] = array ( 'brand_id' => $key, 'brand_name' => $brand,'selectID'=>0 );
                }
                ksort ( $brands );
                $cateIds           = $this->getCategory ( $model, $res[ 'cateIds' ] );
                $res[ 'brandIds' ] = $brands;
                $res[ 'cateIds' ]  = $cateIds;
                //获取商品的id
                foreach ( $res['goods'] as $temp ){
                    $ids[] = $temp['goods_id'];
                }
                $sql ="SELECT goods_id,default_image FROM ".DB_PREFIX."goods WHERE goods_id in ( ".implode (',', $ids)." ) ORDER BY field(goods_id,".implode (',', $ids).")";
                $data =$model->getAll($sql);
                //添加商品对应的图片
                foreach($data as $key => $value){
                    $res['goods'][$key]['default_image'] =$this->common->isMySelfImage($value['default_image'], DISCOVERY_GOODS_IMG);
                }
                //喜欢数量的问题
                foreach($res['goods'] as $key=>$value){
                    $res['goods'][$key]['collects']=$value['jcollects']+$value['collects'];
                    $sql = "SELECT COUNT(*) as t FROM ".DB_PREFIX."collect where user_id={$user_id} and type='goods' and  item_id={$value['goods_id']}";
                    $res['goods'][$key]['follow'] = $model->getOne($sql)?1:0;

                }
                $this->ajax_return ( FLAG_OK, '', $res );
            }
            else
            {
                $this->ajax_return ( FLAG_ERROR, '暂无结果！' );
            }


        }

        /**
         * 搜索指定数据
         *
         * @param $word
         * @param $cate_id
         * @param $brand_id
         * @param $min
         * @param $max
         * @param $sort_id
         * @param $store_id
         * @param $page
         *
         * @return array
         * @Author     lz
         * @Date&time  2016/1/6
         */
        public function searching ( $word, $cate_id, $brand_id, $min,$max, $sort_id, $store_id, $page )
        {
            $keyArr = $sort = $range = array ();
            //搜索关键词
            if ( $word )
            {
                $keyArr[] = $word;
            }
            //拼装分类条件
            if ( $cate_id )
            {
                $keyArr[] = $cate_id;
            }
            //拼装分类条件
            if ( $brand_id )
            {
                $keyArr[] = $brand_id;
            }
            //店铺ID条件
            if ( $store_id )
            {
                $keyArr[] = $store_id;
            }

            $keyword = implode ( " AND ", $keyArr );

            //拼装价格区间条件
            if ( $min > 0 && $max > 8 )
            {
                $range      = array ( "field" => "price", "from" => $min, "to" => $max );
            }

            //拼装排序条件
            if ( $sort_id == 2 )
            {
                $sort = array ( "price" => false );
            }
            elseif ( $sort_id == 3 )
            {
                $sort = array ( "price" => true );
            }
            elseif ( $sort_id == 4 )
            {
                $sort = array ( "sales" => false );
            }
            elseif ( $sort_id == 5 )
            {
                $sort = array ( "jcollects" => false );
            }
            elseif ( $sort_id == 1 )
            {
                $sort = array ( "review_time" => true );
            }
            //根据分页去请求指定的数据
            //$page = $page>1?$page:1;

            $client   = $this->rpcConnect ( 3 );
            $facet    = array ( "cate_id_two", "brand_id" );
            $result   = $client->search ( $keyword, $page, $this->size, $sort, $range, $facet,'ios');
            $totalNum = $result[ 'count' ];
            $pages    = ceil ( $totalNum / $this->size );
            if ( $pages > 100 )
            {
                $pages    = 100;
                $totalNum = $pages * $this->size;
            }

            return array (
                "goods"    => $result[ 'data' ],
                "pages"    => $pages,
                'totalNum' => $totalNum,
                "cateIds"  => $result[ 'cate_id_two' ],
                "brandIds" => $result[ 'brand_id' ]
            );
        }

        /**
         * 获取价格列表
         * @return array
         * @author jyx
         * @date   2015/12/01
         */
        public function getPrice ()
        {
            return array (
                '1' => array ( 'price_id' => 1, 'min' => 0, 'max' => 500,'selectID'=>0 ),
                '2' => array ( 'price_id' => 2, 'min' => 500, 'max' => 1000,'selectID'=>0 ),
                '3' => array ( 'price_id' => 3, 'min' => 1000, 'max' => 5000 ,'selectID'=>0),
                '4' => array ( 'price_id' => 4, 'min' => 5000, 'max' => 10000 ,'selectID'=>0),
                '5' => array ( 'price_id' => 5, 'min' => 10000, 'max' => 30000 ,'selectID'=>0),
                '6' => array ( 'price_id' => 6, 'min' => 30000, 'max' => 30000000 ,'selectID'=>0),
            );
        }

        /**
         * RPC连接
         *
         * @param int $retry
         *
         * @return bool|Yar_Client
         * @Author     lz
         * @Date&time  2016/2/2
         */
        public function rpcConnect ( $retry = 3 )
        {
            try
            {
                $client = new Yar_Client( RPC_SERVER );
                $client->SetOpt ( YAR_OPT_CONNECT_TIMEOUT, 10000 );

                return $client;

            }
            catch ( Exception $e )
            {
                if ( $retry > 0 )
                {
                    $this->rpcConnect ( -- $retry );
                }
                else
                {
                    $this->ajax_return ( FLAG_ERROR, '网络有连接问题！' );
                }
            }
        }

        /**
         * 查询分类
         *
         * @param $model
         *
         * @return mixed
         * @author jyx
         * @date   2015/12/01
         */
        private function getCategory ( $model, $cateIds )
        {

            $cate = array();
            foreach ( $cateIds as $key => $val )
            {
                $cate[] = "$key";
            }
            $sql      = "SELECT cate_id,cate_name,english_name FROM " . DB_PREFIX . "gcategory WHERE store_id=0
                AND parent_id=0 AND if_show=1 ORDER BY sort_order DESC";
            $category = $model->getAll ( $sql );
            if ( $category )
            {
                foreach ( $category as $key => $val )
                {
                    $val[ 'name' ] = $val[ 'cate_name' ] . '/' . trim ( mb_strtoupper ( $val[ 'english_name' ], 'utf8' ), ' ' );
                    $sql           = "SELECT cate_id,cate_name,english_name FROM " . DB_PREFIX . "gcategory WHERE store_id=0
                        AND parent_id={$val['cate_id']} AND if_show=1 ORDER BY sort_order DESC";
                    $sub           = $model->getAll ( $sql );
                    $subs          = array();
                    if ( $sub )
                    {
                        foreach ( $sub as $k => $v )
                        {
                            if ( in_array ( $v[ 'cate_id' ], $cate ) )
                            {
                                $v[ 'name' ] = $v[ 'cate_name' ] . '/' . trim ( mb_strtoupper ( $v[ 'english_name' ], 'utf8' ), ' ' );
                                $v['selectID']=0;
                                $subs[]      = $v;
                            }
                        }
                    }
                    $val[ 'sub' ]     = $subs;
                    $category[ $key ] = $val;
                }
            }
            //去除没有任何商品的一级分类
            $categorys = array();
            foreach ( $category as $val )
            {
                if ( $val[ 'sub' ] )
                {
                    $categorys[] = $val;
                }
            }

            return $categorys;
        }

        /**
         * 搜索数据
         * @author jiayanxiu
         * @date   2015/06/09
         */
        public function search ()
        {
            $action = '搜索数据';
            setLogParameter($action);
            $method = strtoupper ( $_SERVER[ 'REQUEST_METHOD' ] );
            if ( $method != 'GET' )
            {
                $this->ajax_return ( FLAG_ERROR, '非法操作！' );
            }

            $content = $this->get_gp ( 'content', 'G' );
            $offset  = $this->get_gp ( 'offset', 'G' );
            $size    = $this->get_gp ( 'size', 'G' );

            $filter = $this->get_gp ( 'filter', 'G' );//筛选
            //分类
            $cate_id1 = $this->get_gp ( 'cate_id1', 'G' );//一级分类
            $cate_id2 = $this->get_gp ( 'cate_id2', 'G' );//二级分类
            //品牌
            $brand_id = $this->get_gp ( 'brand_id', 'G' );
            //价格
            $min = $this->get_gp ( 'min', 'G' );//最小价格
            $max = $this->get_gp ( 'max', 'G' );//最大价格

            $sort = $this->get_gp ( 'sort', 'G' );//排序,0:默认排序,1:价钱从高到低,2:价钱从底到高,3:销量最高排序,4:喜欢的最多,5:折扣最高

            if ( ! $content )
            {
                $this->ajax_return ( FLAG_ERROR, '您搜索的内容不能为空！' );
            }

            $offset    = ( $offset > 0 ) ? intval ( $offset ) : 0;
            $size      = ( $size > 0 ) ? intval ( $size ) : 10;
            $condition = $order = '';
            if ( $filter == 1 )
            {
                if ( $cate_id1 && $cate_id2 )
                {
                    $condition .= " AND g.cate_id={$cate_id2}";
                }
                elseif ( $cate_id1 && ! $cate_id2 )
                {
                    $condition .= " AND g.cate_id_1={$cate_id1}";
                }
            }
            elseif ( $filter == 2 )
            {
                $condition .= " AND g.brand_id={$brand_id}";
            }
            elseif ( $filter == 3 )
            {
                $condition .= " AND g.price BETWEEN {$min} AND {$max}";
            }
            if ( $sort == 1 )
            {
                $order .= 'g.price DESC';
            }
            elseif ( $sort == 2 )
            {
                $order .= "g.price ASC";
            }
            elseif ( $sort == 3 )
            {
                $order .= 'gs.sales DESC';
            }
            elseif ( $sort == 4 )
            {
                $order .= 'gs.collect DESC';
            }
            elseif ( $sort == 5 )
            {
                $order .= 'g.act_rate DESC';
            }
            else
            {
                $order .= 'g.goods_id DESC';
            }
            //先查询出已经审核的商品，然后再两个表结合查询
            $model   = m ( 'goods' );
            $user_id = $this->checkLogin ();
            //暂时只搜索商品名称和品牌和标签
            $sql
                  = "SELECT g.goods_id,g.goods_name,g.introduction,g.brand,g.price,g.default_image,g.source,g.currency,g.tags,g.store_id,
            g.is_act,g.act_start_time,g.act_end_time,gs.collects,gs.base_collects FROM " . DB_PREFIX . "goods g
            LEFT JOIN " . DB_PREFIX . "goods_statistics gs ON g.goods_id=gs.goods_id WHERE g.if_examine = 1 AND g.if_finance = 1
            AND g.if_show = 1 AND g.closed = 0 {$condition} AND (g.goods_name LIKE '%{$content}%' OR g.brand LIKE '%{$content}%'
            OR g.tags LIKE '%{$content}%') ORDER BY {$order} LIMIT {$offset},{$size}";
            $data = $model->getAll ( $sql );
            //获取关注的商铺的id
            if ( $data )
            {
                $goods_ids = array();
                foreach ( $data as $key => $val )
                {
                    //获取商铺的logo
                    $sql                    = "SELECT store_logo FROM " . DB_PREFIX . "store WHERE store_id={$val['store_id']}";
                    $store                  = $model->getRow ( $sql );
                    $val[ 'store_logo' ]    = $store[ 'store_logo' ] ? QINIU_URL . $store[ 'store_logo' ] . STORE_LOGO : '';
                    $val[ 'collects' ]      = $val[ 'collects' ] + $val[ 'base_collects' ];
                    $val[ 'default_image' ] = $this->common->isMySelfImage ( $val[ 'default_image' ], GOODS_IMG );
                    //获取商品扩展属性信息的
                    $sql = "SELECT goods_id,price,discount_spec_price,is_show_discount FROM " . DB_PREFIX . "goods_spec
                        WHERE goods_id={$val['goods_id']} LIMIT 1";
                    $tmp = $model->getRow ( $sql );
                    //是否是优惠信息
                    $val[ 'discount' ]       = $this->common->isAct ( $tmp, false );
                    $val[ 'discount_price' ] = $val[ 'discount' ] == 1 ? $tmp[ 'discount_spec_price' ] : '0';
                    //是否收藏此商品
                    $val[ 'follow' ] = $user_id ? $this->common->getRelationShip ( $user_id, $val[ 'goods_id' ] ) : 0;
                    $data[ $key ]    = $val;
                    $goods_ids[]     = $val[ 'goods_id' ];
                }
            }
            $this->ajax_return ( FLAG_OK, '', $data );
        }

        /**
         * 有关搜索的标签
         * @author jyx
         * 2015/08/07
         */
        public function tag ()
        {
            $action = '有关搜索的标签';
            setLogParameter($action);
            $method = strtoupper ( $_SERVER[ 'REQUEST_METHOD' ] );
            if ( $method != 'GET' )
            {
                $this->ajax_return ( FLAG_ERROR, '非法操作！' );
            }
            $hot     = array (
                'name' => '热门商品',
                'data' => array (
                    '直邮',
                    '意大利',
                    '珍珠',
                    '熊乃瑾',
                    '长袖',
                    '开衫',
                    '外套',
                    '虎头',
                    '短靴',
                    '印花',
                    '紧身',
                ),
            );
            $hotshop = array (
                'name' => '热门品牌',
                'data' => array ( 'FANCYCD', 'NOLAN HERA', 'CROCUS', 'WEISS', 'ZEUSE', '红吉定制礼服', '花不脱', '金莎&爱唯施' ),
            );
            $data    = array();
            $data[]  = $hot;
            $data[]  = $hotshop;
            $this->ajax_return ( FLAG_OK, '', $data );
        }

        /**
         * 搜索筛选条件
         * @author jyx
         * @date   2015/12/31
         */
        /*public function filter ()
        {
            $action = '搜索筛选条件';
            setLogParameter($action);
            $data  = array ();
            $model = m ( 'goods' );
            $type  = $this->get_gp ( 'type', 'P' );
            $type  = $type ? intval ( $type ) : 0;
            if ( $type == 1 )
            {
                //查询分类
                $data = $this->getCategory ( $model, array() );
            }
            elseif ( $type == 2 )
            {
                //查询品牌
                $data = $this->getBrand ( $model );
            }
            elseif ( $type == 3 )
            {
                //查询价格
                $data = $this->getPrice ();
            }
            $this->ajax_return ( FLAG_OK, '', $data );
        }*/

        /**
         * 获取品牌
         *
         * @param $model
         *
         * @return mixed
         * @author jyx
         * @date   2015/12/01
         */
        private function getBrand ( $model )
        {
            require ROOT_PATH . '/includes/libraries/translate.lib.php';
            $data  = $tmp = array ();
            $sql   = "SELECT brand_id,brand_name,en_name FROM " . DB_PREFIX . "brand WHERE store_id=0 AND if_show=1 ORDER BY sort_order DESC";
            $brand = $model->getAll ( $sql );
            if ( $brand )
            {
                foreach ( $brand as $key => $val )
                {
                    $val[ 'brand_name' ] = trim ( $val[ 'brand_name' ], ' ' );
                    $val[ 'en_name' ]    = trim ( $val[ 'en_name' ] );
                    if ( $val[ 'brand_name' ] && $val[ 'en_name' ] )
                    {
                        $val[ 'name' ] = $val[ 'brand_name' ] . '/' . $val[ 'en_name' ];
                    }
                    elseif ( $val[ 'brand_name' ] && ! $val[ 'en_name' ] )
                    {
                        $val[ 'name' ] = $val[ 'brand_name' ];
                    }
                    elseif ( ! $val[ 'brand_name' ] && $val[ 'en_name' ] )
                    {
                        $val[ 'name' ] = $val[ 'en_name' ];
                    }
                    $val[ 'words' ] = trim ( mb_strtoupper ( Translate::get_words ( $val[ 'name' ] ), 'utf-8' ), ' ' );
                    if ( $val[ 'words' ] )
                    {
                        $list[ $val[ 'words' ] ] = $val;
                    }
                    else
                    {
                        $list[ $val[ 'brand_id' ] ] = $val;
                    }
                }
                //按字母进行排序
                ksort ( $list );
                foreach ( $list as $k => $v )
                {
                    $word = mb_substr ( $v[ 'words' ], 0, 1, 'utf-8' );
                    if ( preg_match ( '/^[A-Z]$/', $word ) )
                    {
                        $tmp[ $word ][] = $v;
                    }
                    else
                    {
                        $tmp[ '#' ][] = $v;
                    }
                }
                foreach ( $tmp as $keys => $value )
                {
                    $data[ 0 ][] = $keys;
                    $data[ 1 ][] = $value;
                }
            }

            return $data;
        }

        /**
         * 获取价格信息
         * @author lz
         * @date   2016-2-3
         */
        public function price ()
        {
            $action = '获取价格信息';
            setLogParameter($action);
            $price = $this->getPrice ();
            $price = array_values ( $price );
            $this->ajax_return ( FLAG_OK, '', $price );
        }

        /**
         * 获取排序字段
         * @author lz
         * @date   2016-2-3
         */
        public function sort ()
        {
            $action = '获取排序字段';
            setLogParameter($action);
            $sort = array (
                array ( 'sort_id' => 1, 'sort_name' => "最新上架", "en_name" => "NEWEST" ),
                array ( 'sort_id' => 2, 'sort_name' => "价格按高到低", "en_name" => "HIGHEST PRICE" ),
                array ( 'sort_id' => 3, 'sort_name' => "价格按低到高", "en_name" => "LOWEST PRICE" ),
                array ( 'sort_id' => 4, 'sort_name' => "销量最多", "en_name" => "BEST SELLER" ),
                array ( 'sort_id' => 5, 'sort_name' => "喜欢最多", "en_name" => "MOST LIKED" ),
            );
            $this->ajax_return ( FLAG_OK, '', $sort );
        }
    }